//
//  IMDeviceInfoService.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/27.
//

#import "IMDeviceInfoService.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import <AdSupport/AdSupport.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <sys/utsname.h>

#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
#endif

@interface IMDeviceInfoService ()

@property (nonatomic, strong) dispatch_queue_t deviceQueue;
@property (nonatomic, copy, nullable) NSString *cachedCountryCode;
@property (nonatomic, strong, nullable) IMCountryInfo *cachedCountryInfo;

@end

@implementation IMDeviceInfoService

static IMDeviceInfoService *_sharedService = nil;
static dispatch_once_t _onceToken;

+ (instancetype)sharedService {
    dispatch_once(&_onceToken, ^{
        _sharedService = [[IMDeviceInfoService alloc] init];
    });
    return _sharedService;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _deviceQueue = dispatch_queue_create("com.dualmediationsdk.device", DISPATCH_QUEUE_SERIAL);
        [IMLogUtils info:IMLogTagAd format:@"IMDeviceInfoService initialized"];
    }
    return self;
}

#pragma mark - GAID相关

- (NSString *)getGAID {
    // iOS没有GAID概念，这里返回IDFA作为替代
    // 在实际项目中，如果需要真正的GAID，需要通过服务端API获取
    NSString *idfa = [self getIDFA];
    if (idfa && ![idfa isEqualToString:@"00000000-0000-0000-0000-000000000000"]) {
        [IMLogUtils info:IMLogTagAd format:@"获取GAID成功（使用IDFA）: %@", idfa];
        return idfa;
    }
    
    // 如果IDFA不可用，使用IDFV
    NSString *idfv = [self getIDFV];
    if (idfv) {
        [IMLogUtils info:IMLogTagAd format:@"获取GAID成功（使用IDFV）: %@", idfv];
        return idfv;
    }
    
    [IMLogUtils warning:IMLogTagAd format:@"获取GAID失败：设备标识符不可用"];
    return nil;
}

- (void)getGAIDWithCompletion:(IMDeviceInfoCompletionBlock)completion {
    dispatch_async(self.deviceQueue, ^{
        NSString *gaid = [self getGAID];
        
        IMDeviceInfoResult *result;
        if (gaid) {
            result = [IMDeviceInfoResult successWithData:gaid];
        } else {
            result = [IMDeviceInfoResult failureWithCode:-2001 message:@"无法获取GAID"];
        }
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(result);
            });
        }
    });
}

- (BOOL)isGAIDAvailable {
    return [self getGAID] != nil;
}

#pragma mark - 国家代码相关

- (NSString *)getCountryCode {
    IMCountryInfo *countryInfo = [self getCountryInfo];
    return countryInfo.countryCode;
}

- (IMCountryInfo *)getCountryInfo {
    if (self.cachedCountryInfo) {
        return self.cachedCountryInfo;
    }
    
    // 优先使用Locale获取
    NSString *countryCode = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    NSString *countryName = [[NSLocale currentLocale] displayNameForKey:NSLocaleCountryCode value:countryCode];
    
    if (countryCode && countryCode.length == 2) {
        self.cachedCountryInfo = [IMCountryInfo infoWithCountryCode:countryCode.uppercaseString 
                                                        countryName:countryName 
                                                             source:@"Locale"];
        [IMLogUtils info:IMLogTagAd format:@"获取国家信息成功（Locale）: %@", self.cachedCountryInfo];
        return self.cachedCountryInfo;
    }
    
    // 备用方案：使用时区推测
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    NSString *timeZoneName = timeZone.name;
    
    // 简单的时区到国家代码映射
    NSDictionary *timezoneToCountry = @{
        @"Asia/Shanghai": @"CN",
        @"America/New_York": @"US",
        @"Europe/London": @"GB",
        @"Asia/Tokyo": @"JP",
        @"Asia/Seoul": @"KR",
        @"Europe/Berlin": @"DE",
        @"Europe/Paris": @"FR",
        @"Australia/Sydney": @"AU"
    };
    
    NSString *fallbackCountryCode = timezoneToCountry[timeZoneName];
    if (fallbackCountryCode) {
        self.cachedCountryInfo = [IMCountryInfo infoWithCountryCode:fallbackCountryCode 
                                                        countryName:nil 
                                                             source:@"TimeZone"];
        [IMLogUtils info:IMLogTagAd format:@"获取国家信息成功（TimeZone）: %@", self.cachedCountryInfo];
        return self.cachedCountryInfo;
    }
    
    // 最后的备用方案
    self.cachedCountryInfo = [IMCountryInfo infoWithCountryCode:@"US" 
                                                    countryName:@"United States" 
                                                         source:@"Default"];
    [IMLogUtils warning:IMLogTagAd format:@"使用默认国家信息: %@", self.cachedCountryInfo];
    return self.cachedCountryInfo;
}

- (void)getCountryInfoWithCompletion:(IMDeviceInfoCompletionBlock)completion {
    dispatch_async(self.deviceQueue, ^{
        IMCountryInfo *countryInfo = [self getCountryInfo];
        IMDeviceInfoResult *result = [IMDeviceInfoResult successWithData:countryInfo];
        
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(result);
            });
        }
    });
}

- (void)getCountryCodeByIPWithCompletion:(IMDeviceInfoCompletionBlock)completion {
    // 通过IP获取国家代码（需要网络请求）
    // 这里提供一个示例实现，实际项目中可以使用更可靠的IP地理位置服务
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:@"http://ip-api.com/json/?fields=countryCode"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
        
        NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            
            IMDeviceInfoResult *result;
            
            if (error) {
                [IMLogUtils error:IMLogTagAd format:@"通过IP获取国家代码失败: %@", error.localizedDescription];
                result = [IMDeviceInfoResult failureWithCode:-2002 message:error.localizedDescription];
            } else if (data) {
                @try {
                    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                    NSString *countryCode = json[@"countryCode"];
                    
                    if (countryCode && countryCode.length == 2) {
                        IMCountryInfo *countryInfo = [IMCountryInfo infoWithCountryCode:countryCode.uppercaseString 
                                                                            countryName:nil 
                                                                                 source:@"IP"];
                        result = [IMDeviceInfoResult successWithData:countryInfo];
                        [IMLogUtils info:IMLogTagAd format:@"通过IP获取国家代码成功: %@", countryCode];
                    } else {
                        result = [IMDeviceInfoResult failureWithCode:-2003 message:@"IP服务返回无效数据"];
                    }
                } @catch (NSException *exception) {
                    result = [IMDeviceInfoResult failureWithCode:-2004 message:@"解析IP服务响应失败"];
                }
            } else {
                result = [IMDeviceInfoResult failureWithCode:-2005 message:@"IP服务无响应"];
            }
            
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion(result);
                });
            }
        }];
        
        [task resume];
    });
}

#pragma mark - 屏幕设备相关

- (BOOL)isShortDevice {
    IMDeviceScreenInfo *screenInfo = [self getScreenInfo];
    return screenInfo.isShortDevice;
}

- (BOOL)isShortDeviceForViewController:(UIViewController *)viewController {
    IMDeviceScreenInfo *screenInfo = [self getScreenInfoForViewController:viewController];
    return screenInfo.isShortDevice;
}

- (IMDeviceScreenInfo *)getScreenInfo {
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    CGFloat scale = [UIScreen mainScreen].scale;
    
    CGFloat width = screenBounds.size.width * scale;
    CGFloat height = screenBounds.size.height * scale;
    
    IMDeviceScreenInfo *screenInfo = [IMDeviceScreenInfo infoWithWidth:width height:height];
    [IMLogUtils info:IMLogTagAd format:@"获取屏幕信息: %@", screenInfo];
    
    return screenInfo;
}

- (IMDeviceScreenInfo *)getScreenInfoForViewController:(UIViewController *)viewController {
    if (!viewController || !viewController.view) {
        return [self getScreenInfo];
    }
    
    CGRect bounds = viewController.view.bounds;
    CGFloat scale = viewController.view.contentScaleFactor;
    
    CGFloat width = bounds.size.width * scale;
    CGFloat height = bounds.size.height * scale;
    
    IMDeviceScreenInfo *screenInfo = [IMDeviceScreenInfo infoWithWidth:width height:height];
    [IMLogUtils info:IMLogTagAd format:@"获取视图控制器屏幕信息: %@", screenInfo];
    
    return screenInfo;
}

#pragma mark - 设备标识相关

- (NSString *)getIDFA {
    if (@available(iOS 14, *)) {
        if ([ATTrackingManager trackingAuthorizationStatus] == ATTrackingManagerAuthorizationStatusAuthorized) {
            return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        } else {
            [IMLogUtils warning:IMLogTagAd format:@"IDFA访问被拒绝，状态: %ld", (long)[ATTrackingManager trackingAuthorizationStatus]];
            return nil;
        }
    } else {
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
        } else {
            [IMLogUtils warning:IMLogTagAd format:@"广告跟踪被禁用"];
            return nil;
        }
    }
}

- (NSString *)getIDFV {
    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}

- (NSString *)getDeviceModel {
    struct utsname systemInfo;
    uname(&systemInfo);
    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}

- (NSString *)getSystemVersion {
    return [[UIDevice currentDevice] systemVersion];
}

#pragma mark - 综合设备信息

- (NSDictionary *)getDeviceInfo {
    NSMutableDictionary *deviceInfo = [NSMutableDictionary dictionary];
    
    // 基本设备信息
    deviceInfo[@"device_model"] = [self getDeviceModel] ?: @"Unknown";
    deviceInfo[@"system_version"] = [self getSystemVersion] ?: @"Unknown";
    deviceInfo[@"system_name"] = [[UIDevice currentDevice] systemName] ?: @"iOS";
    deviceInfo[@"device_name"] = [[UIDevice currentDevice] name] ?: @"Unknown";
    
    // 标识符信息
    NSString *idfa = [self getIDFA];
    deviceInfo[@"idfa"] = idfa ?: @"Not Available";
    deviceInfo[@"idfv"] = [self getIDFV] ?: @"Not Available";
    deviceInfo[@"gaid"] = [self getGAID] ?: @"Not Available";
    
    // 地理信息
    deviceInfo[@"country_code"] = [self getCountryCode] ?: @"Unknown";
    
    // 屏幕信息
    IMDeviceScreenInfo *screenInfo = [self getScreenInfo];
    deviceInfo[@"screen_width"] = @(screenInfo.screenWidth);
    deviceInfo[@"screen_height"] = @(screenInfo.screenHeight);
    deviceInfo[@"is_short_device"] = @(screenInfo.isShortDevice);
    
    [IMLogUtils info:IMLogTagAd format:@"获取设备基本信息完成"];
    return [deviceInfo copy];
}

- (NSDictionary *)getDetailedDeviceInfo {
    NSMutableDictionary *detailedInfo = [[self getDeviceInfo] mutableCopy];
    
    // 添加详细信息
    UIDevice *device = [UIDevice currentDevice];
    detailedInfo[@"device_orientation"] = @(device.orientation);
    detailedInfo[@"battery_level"] = @(device.batteryLevel);
    detailedInfo[@"battery_state"] = @(device.batteryState);
    detailedInfo[@"multitasking_supported"] = @(device.multitaskingSupported);
    
    // 屏幕详细信息
    UIScreen *screen = [UIScreen mainScreen];
    detailedInfo[@"screen_scale"] = @(screen.scale);
    detailedInfo[@"screen_brightness"] = @(screen.brightness);
    
    // 内存信息
    NSProcessInfo *processInfo = [NSProcessInfo processInfo];
    detailedInfo[@"physical_memory"] = @(processInfo.physicalMemory);
    detailedInfo[@"processor_count"] = @(processInfo.processorCount);
    detailedInfo[@"active_processor_count"] = @(processInfo.activeProcessorCount);
    
    // 应用信息
    NSBundle *bundle = [NSBundle mainBundle];
    detailedInfo[@"app_version"] = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"] ?: @"Unknown";
    detailedInfo[@"app_build"] = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"] ?: @"Unknown";
    detailedInfo[@"bundle_identifier"] = bundle.bundleIdentifier ?: @"Unknown";
    
    // 时区信息
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    detailedInfo[@"timezone_name"] = timeZone.name ?: @"Unknown";
    detailedInfo[@"timezone_offset"] = @(timeZone.secondsFromGMT);
    
    // 语言信息
    NSArray *languages = [NSLocale preferredLanguages];
    detailedInfo[@"preferred_language"] = languages.firstObject ?: @"Unknown";
    detailedInfo[@"locale_identifier"] = [[NSLocale currentLocale] localeIdentifier] ?: @"Unknown";
    
    [IMLogUtils info:IMLogTagAd format:@"获取设备详细信息完成"];
    return [detailedInfo copy];
}

- (NSDictionary *)getNetworkInfo {
    NSMutableDictionary *networkInfo = [NSMutableDictionary dictionary];
    
    // 网络可达性状态（简化版本）
    networkInfo[@"network_available"] = @YES; // 简化实现，实际项目中可以使用Reachability
    
    // 获取WiFi信息（需要添加相关权限和框架）
    networkInfo[@"connection_type"] = @"Unknown";
    networkInfo[@"wifi_ssid"] = @"Not Available";
    networkInfo[@"carrier_name"] = @"Not Available";
    
    // 网络状态检测
    @try {
        // 尝试创建一个简单的网络连接来检测网络状态
        NSURL *url = [NSURL URLWithString:@"https://www.apple.com"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
        
        // 使用信号量实现同步请求
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSHTTPURLResponse *response = nil;
        __block NSError *error = nil;
        
        NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *urlResponse, NSError *taskError) {
            response = (NSHTTPURLResponse *)urlResponse;
            error = taskError;
            dispatch_semaphore_signal(semaphore);
        }];
        
        [task resume];
        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC));
        
        if (error) {
            networkInfo[@"network_available"] = @NO;
            networkInfo[@"network_error"] = error.localizedDescription;
        } else {
            networkInfo[@"network_available"] = @YES;
            networkInfo[@"http_status_code"] = @(response.statusCode);
        }
    } @catch (NSException *exception) {
        networkInfo[@"network_available"] = @NO;
        networkInfo[@"network_error"] = exception.reason;
    }
    
    // 添加时间戳
    networkInfo[@"check_timestamp"] = @([[NSDate date] timeIntervalSince1970]);
    
    [IMLogUtils info:IMLogTagAd format:@"获取网络信息完成"];
    return [networkInfo copy];
}

@end